<template>
  <div>
    <el-dialog
      ref="isPopWindows"
      v-dialogDrag
      :title="textMap[popupsState]"
      :visible.sync="isViewPopWindows"
      width="90%"
      :append-to-body="true"
      :close-on-click-modal="false"
      center
      @close="close"
      @opened="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="formBoxContain">
        <!--
            buttons: 按钮
            froms: 表单
            fromsField: 表单对应的字段
            tableOption: 网格项
            dynamicApiConfigs: 取值
         -->
        <one-table-template
          ref="isPopWindowsTable"
          :dynamic-buttons="buttons"
          :dynamic-components="tableComponents"
          :dynamic-form-fields="fromsField"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="false"
          :dynamic-is-fix-choose="false"
          :dynamic-is-fix-index="false"
          :dynamic-api-style="'restfuls'"
        />
        <div class="bottom_contain_box">
          <div class="box_item1">
            <calendar-by-year
              :key="calendarKey"
              ref="calendar"
              :options="calendarArr"
              class="calendar"
              :determine-year="fromsField.calendarYear"
              :set-calendar-data="setCalendarData"
              @getCalendarData="getCalendarData"
              @handlePrevYear="handlePrevYear"
              @handleNextYear="handleNextYear"
            />
          </div>
          <div class="box_item2">
            <one-table-template
              ref="isPopWindowsTable"
              :dynamic-table-defult-height="650"
              :dynamic-table-cols="tableOption"
              :dynamic-is-show-select="true"
              :dynamic-is-init-table="false"
              :dynamic-is-fix-choose="false"
              :dynamic-is-fix-index="false"
              :is-show-pagination="false"
              :callback-obj="callbackObj"
            />
          </div>
        </div>
      </div>
    </el-dialog>
    <select-website
      :is-view-website="isViewWebsite"
      @selectiondataPart="selectiondata2"
      @close="closeWebsite"
    />
  </div>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import SelectWebsite from './selectWebsite'
import calendarByYear from '@/views/pa/purchasingManagement/orderCalendarSetting/cans/calendarByYear'
import api from './api'

export default {
  components: {
    calendarByYear,
    dialogHeader,
    OneTableTemplate,
    SelectWebsite
  },
  props: {
    // 是否关闭弹窗
    isViewPopWindows: {
      type: Boolean,
      default: false
    },
    popupsState: {
      type: String
    },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    null
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      calendarKey: this.$utils.generateId(),
      calendarArr: {
        type: 'combination',
        headStyle: {
          todayBtn: 'right',
          combination: 'center',
          checkBtn: 'right'
        },
        viewStyle: {
          day: 'center'
        },
        calendarData: []
      },
      setCalendarData: [],
      selection: null,
      isViewWebsite: false,
      // dynamicApiConfigs: vehiclePdiPriceInquirys.queryOrderCalendarDetail,
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '日历名称:',
              codeField: 'calendarName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey2',
              labelName: '日历年份:',
              codeField: 'calendarYear',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'year',
              format: 'yyyy',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'c,n',
              options: [
                { c: '0', n: '停用' },
                { c: '1', n: '启用' }
              ],
              type: 'inputText',
              isMust: true,
              span: 6
            }
          ],
      fromsField: {
        calendarName: '', // 日历名称
        calendarYear: '', // 日历年份
        isEnable: '' // 状态
      },
      // 标题
      textMap: {
        edit: '订货日历编辑',
        add: '订货日历新增'
      },
      buttons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => {
            const loading = this.$loading({ text: `请稍等...` })
            let url = api.updatePlaceOrderCalendarDetailUsingPOST.APIUrl
            if (this.popupsState === 'edit') {
              url = api.editCalendar.APIUrl
            }
            const res = this.parseSelectDate(this.selectData)
            let params = {
              ...this.fromsField,
              calendarList: res,
              dealerList: this.$refs['isPopWindowsTable'].list
            }
            if (this.popupsState === 'edit') {
              url = api.editCalendar.APIUrl
              params.orderCalendarId = this.dynamicEditRowData.orderCalendarId
              params.updateControlId = this.dynamicEditRowData.updateControlId
            }
            this.$requestAPI({
              apiUrl: url,
              variables: params
            }).then(res => {
              if (res.result === '1') {
                this.close()
                this.$parent.queryTable()
              } else {
                this.$message(res.msg ? res.msg : '')
              }
            }).catch(err => {
              if (err.response.data.msg) {
                this.$message(err.response.data.msg)
              } else {
                this.$message(err.message)
              }
            }).finally(() => {
              loading.close()
            })
          },
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'button2',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => {
            this.close()
          },
          text: '取消',
          position: 'right'
        },
        {
          compKey: 'button3',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => {
            this.isViewWebsite = true
          },
          text: '增加网点',
          position: 'right'
        },
        {
          compKey: 'button4',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => this.delete(),
          text: '删除网点',
          position: 'right'
        },
        // {
        //   calendarName: '',
        //   calendarYear: '',
        //   status: '',
        //   calendarList: [],
        //   xxxxList: []
        // },
        {
          compKey: 'button5',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => {
            const calenComp = this.$refs['calendar']
            const workDay = ['一', '二', '三', '四', '五']
            for (let i = 0; i < 12; i++) {
              for (let j = 0; j < 5; j++) {
                calenComp.selectByWeek({
                  name: workDay[j]
                }, calenComp['calendarList'][i])
              }
            }
          },
          text: '工作日全选',
          position: 'left'
        },
        {
          compKey: 'button6',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => {
            debugger
            const calenComp = this.$refs['calendar']
            for (let i = 0; i < 12; i++) {
              calenComp.selectByWeek({
                name: '六'
              }, calenComp['calendarList'][i])
            }
          },
          text: '周六全选',
          position: 'left'
        },
        {
          compKey: 'button7',
          type: '',
          size: 'small',
          name: '',
          clickEvent: () => {
            const calenComp = this.$refs['calendar']
            for (let i = 0; i < 12; i++) {
              calenComp.selectByWeek({
                name: '日'
              }, calenComp['calendarList'][i])
            }
          },
          text: '周日全选',
          position: 'left'
        }
      ],
      selectData: [],
      tableOption:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableOption &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableOption
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableOption
          : [
            {
              prop: 'dlrCode',
              label: '经销商编码',
              align: 'center'
            },
            {
              prop: 'dlrShortName',
              label: '经销商名称',
              align: 'center'
            }
          ],
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        onRowClick: (currentRow) => {
          this.onRightRowClick(currentRow)
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
          console.log(this.selectiondata, 9999)
        },
        onCheckSelectChange: (selection) => {
          // this.onCheckSelectChange1(selection)
        }
      }
    }
  },
  watch: {
    'fromsField.calendarYear': function (val) {
      this.calendarKey = this.$utils.generateId()
    }
  },
  created() {
    if (this.popupsState === 'edit') {
      const { calendarYear, calendarName, isEnable } = this.dynamicEditRowData
      this.fromsField.calendarYear = calendarYear
      this.fromsField.calendarName = calendarName
      this.fromsField.isEnable = isEnable
      this.loadCalendar()
      this.tableComponents.filter(o => o.codeField === 'calendarYear')[0].disabled = true
    } else {
      this.fromsField.calendarYear = new Date().getFullYear().toString()
    }
  },
  methods: {
    loadCalendar() {
      const { updateControlId, calendarYear, calendarName, isEnable, orderCalendarId } = this.dynamicEditRowData
      this.$requestAPI({
        apiUrl: api.calendarDetail.APIUrl,
        variables: {
          updateControlId, calendarName,
          calendarYear, isEnable, orderCalendarId
        }
      }).then(res => {
        if (res.result === '1') {
          const datas = this.constructionParameters(res.rows[1]['calendarList'], this.fromsField.calendarYear)
          this.setCalendarData = datas
          this.selectData = datas
          this.$refs['isPopWindowsTable'].list = res.rows[2]['dealerList']
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    parseSelectDate(selectData) {
      // 解析日期对象，构造参数
      return selectData.reduce((res, item, idx) => {
        const monthSelect = []
        for (const [k, v] of Object.entries(item)) {
          if (k.startsWith('date') && v === '1') {
            monthSelect.push(item['yearMonths'].slice(0, 4) + '-' + item['yearMonths'].slice(4) + '-' + k.slice(4).padStart(2, 0))
          }
        }
        res.push(monthSelect)
        return res
      }, [])
    },
    constructionParameters(selectDate, year = new Date().getFullYear()) {
      let item = { 'calendarType': '0' }
      for (let i = 1; i < 32; i++) {
        item[`date${i}`] = '0'
      }
      const _item = this.$utils.deepCopy(item)
      return selectDate.reduce((res, arr, idx) => {
        item['yearMonths'] = year + (idx + 1).toString().padStart(2, '0')
        for (let i = 0; i < arr.length; i++) {
          let day = arr[i].split('-')[2]
          if (day.startsWith('0')) {
            day = day.slice(1)
          }
          item[`date` + day] = '1'
        }
        res.push(item)
        item = this.$utils.deepCopy(_item)
        return res
      }, [])
    },
    getCalendarData(data) {
      this.selectData = data
      // console.log(JSON.stringify(this.selectData))
    },
    handlePrevYear(year) {
      this.formField.calendarYear = year
    },
    handleNextYear(year) {
      this.formField.calendarYear = year
    },
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    close() {
      this.$emit('close')
    },
    closeWebsite() {
      this.isViewWebsite = false
    },
    open() {
    },
    // 增加网点
    selectiondata2(selectiondata) {
      selectiondata.forEach((item) => {
        this.$refs.isPopWindowsTable.list.push(item)
      })
    },
    // 删除网点
    delete() {
      if (!this.selectiondata || this.selectiondata.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warn',
          duration: 1000
        })
      } else {
        this.selectiondata.forEach((item) => {
          this.$refs.isPopWindowsTable.list.forEach((element) => {
            if (element == item) {
              this.$refs.isPopWindowsTable.list.splice(element, 1)
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1000
              })
            }
          })
        })
      }
    }
  }
}
</script>
<style scoped>
.formBoxContain {
  height: 750px;
}
.bottom_contain_box {
  height: 670px;
  display: flex;
  justify-content: space-between;
}
.box_item1 {
  width: 69%;
  /*overflow-y: scroll;*/
  /*overflow-x: auto;*/
  height: 670px;
}
.calendar {
  height: 100%;
}
.box_item2 {
  width: 30%;
  height: 98%;
}
</style>
